%% MMG datalogger 05/02/13 EB (TB supervision)
% live trace of mmg data, with csv log files, advantage should mean that
% the bluetooth should work without needing to change the matlab code.
% running at 115200 baud will be ample speed to give a 1khz sample even
% with 2 mmgs, however there may be problems as the system is multiplexed

clear;

%% Define Serial Port Name
port = input ('Input Port Name  ','s');
log = input ('Input Log File Name  ','s');

%% Create & Open Serial Port
SER = serial(port,'Terminator','lf','baud',19200,'DataTerminalReady','off');
%%
fopen(SER);


%% Create Log File

fID=fopen([log,'.csv'],'w+');

% for i = 1:10
%    
% strcat('d',num2str(i)) = fread(SER);
% 
% end
% 
% dTa = cat(2, d1,d2,d3,d4,d5,d6,d7,d8,d9,d10);

%%
figure

%% Read Data

vals=500;

L=zeros(vals,2);
X=1:vals;

current_row=1;

H=0;


  figure;
  H = plot(X,zeros(1,500));
  ylim([0,1024]);
  xlim([0,500]);

fwrite(SER,240);


while 1
    t = fread(SER,1,'uint32');  %read line from serial
    S = fread(SER,1,'uint16');
    
    
    fprintf(fID,'%d,%d\r\n',t,S);
%     fwrite(fID,t,'uint32',0,'l');      		% Write data directly to a file
%     fwrite(fID,S,'uint16',0,'l');
    %disp(current_row);
    L(current_row,:)=[t,S'];     %add data to new line in array
    
    % Get elements of L as a ring buffer
    R=[current_row+1:vals,1:current_row];
    
  
    set(H,'YData',L(R,2));
  
    drawnow;                %force figure to redraw
    
    % Increment buffer position, loop back if at the end
    current_row=mod(current_row,vals)+1;
end
